/******************************************************************************
 * 
 * Announce: CSharpKit, Basic algorithms, components and definitions.
 *           Copyright (C) ShenYongchen.
 *           All rights reserved.
 *   Author: 申永辰.郑州 (shenyczz@163.com)
 *  WebSite: http://gitee.com/shenyczz/csharp_csk
 *
 * THIS CODE IS LICENSED UNDER THE MIT LICENSE (MIT).
 * THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF 
 * ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
 * IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
 * PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
 * 
******************************************************************************/
using System;
using System.Reflection;

namespace CSharpKit.ComponentModel
{
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property,
        AllowMultiple = false, Inherited = false)]
    public sealed class FieldSizeAttribute : Attribute
    {
        public FieldSizeAttribute(int len) { Value = len; }
        public int Value { get; private set; }

        /// <summary>
        /// 获取类/结构字段的 FieldSizeAttribute 自定义属性实例
        /// </summary>
        /// <param name="type">对象类型</param>
        /// <param name="field_name">对象字段名称</param>
        /// <param name="bindingFlags">绑定标记</param>
        /// <returns></returns>
        public static int GetValue(Type type, string field_name, BindingFlags bindingFlags)
        {
            var result = 0;

            try
            {
                var obj = GetObject(type, field_name, bindingFlags);
                if (obj != null) result = obj.Value;
            }
            catch (System.Exception)
            {
                // TODO
            }

            return result;
        }

        /// <summary>
        /// 获取类/结构字段的 FieldSizeAttribute 自定义属性实例
        /// </summary>
        /// <param name="type">对象类型</param>
        /// <param name="field_name">对象字段名称</param>
        /// <param name="bindingFlags">绑定标记</param>
        /// <returns></returns>
        static FieldSizeAttribute GetObject(Type type, string field_name, BindingFlags bindingFlags)
        {
            var result = default(FieldSizeAttribute);

            try
            {
                var mcl = type;
                var fld = mcl.GetField(field_name, bindingFlags);
                var attrs = fld.GetCustomAttributes(false);

                for (var i = 0; i < attrs.Length; i++)
                {
                    var attr = attrs[i];
                    if (attr is FieldSizeAttribute fsa)
                    {
                        result = fsa;
                        break;
                    }
                }
            }
            catch (System.Exception)
            {
                // TODO
            }

            return result;
        }





        //}}@@@
    }







}
